#include "styledtableview.h"
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QSpinBox>
#include <QMessageBox>
#include <QHeaderView>
#include <QDebug>
#include <climits>
#include <QDateTime>
#include <QMetaMethod>

// 构造函数：初始化组件和默认按钮
StyledTableView::StyledTableView(QWidget *parent)
    : QWidget(parent)
{
    tableView = new QTableView(this);
    model = new QStandardItemModel(this);
    mainLayout = new QVBoxLayout(this);

    actionButtons << ActionButtonInfo("存入", "save")
                  << ActionButtonInfo("取出", "take");

    setupUI();
}

// 初始化UI：配置表格属性和布局
void StyledTableView::setupUI()
{
    tableView->setModel(model);
    tableView->setSelectionBehavior(QAbstractItemView::SelectRows);
    tableView->setSelectionMode(QAbstractItemView::SingleSelection);
    tableView->setEditTriggers(QAbstractItemView::NoEditTriggers);
    tableView->horizontalHeader()->setStretchLastSection(true);
    tableView->verticalHeader()->setVisible(false);

    mainLayout->setContentsMargins(0, 0, 0, 0);
    mainLayout->setSpacing(0);
    mainLayout->addWidget(tableView);
    setLayout(mainLayout);

    applyTableStyling();
}

// 应用表格样式：设置表头和表格主体样式
void StyledTableView::applyTableStyling()
{
    tableView->horizontalHeader()->setStyleSheet(
                "QHeaderView::section {"
                "   background-color: #4A90E2;"
                "   color: white; font-weight: bold;"
                "   border: 1px solid #666666; padding: 4px;"
                "}"
                );

    tableView->setStyleSheet(
                "QTableView {"
                "   alternate-background-color: #f9f9f9;"
                "   background-color: #ffffff; border: none;"
                "   gridline-color: #dddddd;"
                "}"
                "QTableView::item { padding: 2px; }"
                );

    tableView->setAlternatingRowColors(true);
}

// 设置表头信息：配置列顺序和标题
void StyledTableView::setHeaders(const QList<QString>& fieldOrder, const QMap<QString, QString>& headerMap)
{
    m_fieldOrder = fieldOrder;
    m_headerMap = headerMap;

    quantityColumnIndex = m_fieldOrder.size();
    actionColumnIndex = m_fieldOrder.size() + 1;

    QStringList fullHeaders;
    for (const QString& field : m_fieldOrder) {
        fullHeaders << m_headerMap.value(field, field);
    }
    fullHeaders << "数量" << "操作";

    model->setColumnCount(fullHeaders.size());
    for (int i = 0; i < fullHeaders.size(); ++i) {
        model->setHeaderData(i, Qt::Horizontal, fullHeaders[i]);
    }
}

// 设置表格数据：更新数据并刷新表格
void StyledTableView::setDataList(const QList<MaterialVO*>& dataList)
{
    m_dataList = dataList;
    updateTableFromEntities();
    refreshTableView();
}

// 从实体更新表格：填充表格数据
void StyledTableView::updateTableFromEntities()
{
    model->setRowCount(0);
    for (const MaterialVO* materialVO : m_dataList) {
        if (!materialVO) continue;

        QList<QStandardItem*> items;
        for (const QString& field : m_fieldOrder) {
            QString displayText;
            const QMetaObject* metaObj = materialVO->metaObject();
            int propertyIndex = metaObj->indexOfProperty(field.toUtf8().constData());

            if (propertyIndex != -1) {
                QVariant value = materialVO->property(metaObj->property(propertyIndex).name());

                if (value.type() == QVariant::DateTime) {
                    displayText = value.toDateTime().toString("yyyy-MM-dd HH:mm:ss");
                } else if (value.type() == QVariant::Date) {
                    displayText = value.toDate().toString("yyyy-MM-dd");
                } else {
                    displayText = value.toString();
                }
            } else {
                QString getterName = QString("get_%1").arg(field);
                int methodIndex = metaObj->indexOfMethod(QMetaObject::normalizedSignature(
                    QString("%1()").arg(getterName).toUtf8().constData()));

                if (methodIndex != -1) {
                    QMetaMethod method = metaObj->method(methodIndex);
                    QVariant returnValue;
                    method.invoke(const_cast<MaterialVO*>(materialVO),
                                 Q_RETURN_ARG(QVariant, returnValue));
                    displayText = returnValue.toString();
                } else {
                    displayText = "";
                }
            }

            QStandardItem* item = new QStandardItem(displayText);
            item->setEditable(false);
            items.append(item);
        }

        items << new QStandardItem("") << new QStandardItem("");
        model->appendRow(items);
    }
}

// 刷新表格视图：更新数量框和操作按钮
void StyledTableView::refreshTableView()
{
    int rowCount = model->rowCount();
    if (rowCount <= 0) return;

    // 更新数量列
    for (int row = 0; row < rowCount; ++row) {
        QModelIndex index = model->index(row, quantityColumnIndex);
        if (!index.isValid()) continue;

        QSpinBox* spinBox = nullptr;
        QWidget* existingWidget = tableView->indexWidget(index);

        if (existingWidget) {
            spinBox = existingWidget->findChild<QSpinBox*>();
        } else {
            spinBox = new QSpinBox(this);
            spinBox->setAlignment(Qt::AlignCenter);
            spinBox->setStyleSheet(R"(
                QSpinBox {
                    border: 1px solid #cccccc;
                    border-radius: 4px;
                    padding: 4px 8px;
                    font-size: 12px;
                }
                QSpinBox:focus {
                    border-color: #4A90E2;
                    outline: none;
                }
            )");
            tableView->setIndexWidget(index, spinBox);
        }

        if (spinBox) {
            spinBox->setRange(0, INT_MAX);
            spinBox->setValue(0);
        }
    }

    // 更新操作列
    for (int row = 0; row < rowCount; ++row) {
        QModelIndex index = model->index(row, actionColumnIndex);
        if (!index.isValid()) continue;

        if (QWidget* oldContainer = tableView->indexWidget(index)) {
            delete oldContainer;
        }

        QWidget* container = new QWidget(this);
        QHBoxLayout* layout = new QHBoxLayout(container);
        layout->setContentsMargins(2, 2, 2, 2);
        layout->setSpacing(6);

        for (const ActionButtonInfo& info : actionButtons) {
            QPushButton* btn = new QPushButton(info.text);
            btn->setFixedHeight(28);
            btn->setMinimumWidth(60);

            if (info.identifier == "save") {
                btn->setStyleSheet(
                            "QPushButton { background-color: #4CAF50; color: white; border-radius: 4px; padding: 2px 8px; font-size: 12px; }"
                            "QPushButton:hover { background-color: #5CBF60; }"
                            );
            } else {
                btn->setStyleSheet(
                            "QPushButton { background-color: #4A90E2; color: white; border-radius: 4px; padding: 2px 8px; font-size: 12px; }"
                            "QPushButton:hover { background-color: #5A9FE2; }"
                            );
            }

            btn->setProperty("row", row);
            btn->setProperty("identifier", info.identifier);
            connect(btn, &QPushButton::clicked, this, &StyledTableView::onActionButtonClicked);
            layout->addWidget(btn);
        }

        container->setLayout(layout);
        tableView->setIndexWidget(index, container);
    }

    // 调整列宽
    for (int col = 0; col < model->columnCount(); ++col) {
        tableView->resizeColumnToContents(col);
        tableView->setColumnWidth(col, qMax(tableView->columnWidth(col), 150));
    }
}

// 操作按钮点击事件处理
void StyledTableView::onActionButtonClicked()
{
    QPushButton* btn = qobject_cast<QPushButton*>(sender());
    if (!btn) return;

    int row = btn->property("row").toInt();
    QString identifier = btn->property("identifier").toString();
    int quantity = getQuantity(row);

    if (row < 0 || row >= m_dataList.size()) {
        QMessageBox::warning(this, "错误", "无效的行索引");
        return;
    }

    if (quantity <= 0) {
        QMessageBox::information(this, "数量错误", "请输入有效的数量（大于0）！");
        return;
    }

    int materialId = getMaterialId(row);
    if (materialId <= 0) {
        QMessageBox::warning(this, "错误", "未找到有效的物料ID，请检查数据！");
        return;
    }

    emit actionButtonClicked(identifier, materialId, quantity, row);
}

// 获取指定行的数量值
int StyledTableView::getQuantity(int row) const
{
    if (row < 0 || row >= model->rowCount()) {
        qDebug() << "[StyledTableView] 无效的数量行索引:" << row;
        return 0;
    }

    QSpinBox* spinBox = qobject_cast<QSpinBox*>(
                tableView->indexWidget(model->index(row, quantityColumnIndex))
                );

    return spinBox ? spinBox->value() : 0;
}

// 获取指定行的物料ID
int StyledTableView::getMaterialId(int row) const
{
    if (row < 0 || row >= m_dataList.size()) {
        qDebug() << "[StyledTableView] 无效的ID行索引:" << row;
        return 0;
    }

    return m_dataList[row]->get_inventory_id();
}
